<?php

/**
 * 微信公众号事件推送处理
 * @description Holp You Do Good But Not Evil
 * @copyright   Copyright 2014-2015 <ycchen@iwshop.cn>
 * @license     LGPL (http://www.gnu.org/licenses/lgpl.html)
 * @author      Chenyong Cai <ycchen@iwshop.cn>
 * @package     Wshop
 * @link        http://www.iwshop.cn
 */

/**
 * @property Wechat $wc Wechat
 * @property Dao $Dao Dao
 * @property Db $Db Db
 */
class EventHandler extends WechatHandler {

    public function run($postObj) {

        /**
         * 处理二维码扫描事件
         * @see http://mp.weixin.qq.com/wiki/14/f79bdec63116f376113937e173652ba2.html#.E6.89.AB.E6.8F.8F.E5.B8.A6.E5.8F.82.E6.95.B0.E4.BA.8C.E7.BB.B4.E7.A0.81.E4.BA.8B.E4.BB.B6
         */
        if ($postObj->Event == "subscribe" || $postObj->Event == "SCAN") {

            $qrscene = '';

            // 获取$qrscene，也就是代理id
            if ($postObj->EventKey && preg_match("/qrscene\_/is", $postObj->EventKey)) {
                // 情景：二维码扫描并且关注公众号
                $qrscene = preg_replace("/qrscene\_/is", "", $postObj->EventKey);
            } else if ($postObj->Event == "SCAN") {
                // 情景：二维码扫描但是<已关注>公众号
                $qrscene = intval($postObj->EventKey);
            }

            if ($qrscene > 0) {
                // 情景Id有效 判断是否已经关联
                $ext = $this->Dao->select()->from(TABLE_COMPANY_USERS)->where(['openid' => $this->openID, 'comid' => $qrscene])->getOneRow();
                if (!$ext) {
                    // 代理用户未加入
                    $this->Db->transtart();
                    try {
                        // 用户是否已注册
                        $user = $this->Dao->select()->from(TABLE_USER)->where(['client_wechat_openid' => $this->openID])->getOneRow();
                        if ($user) {
                            $uid = $user['client_id'];
                            $thiscompany = $this->Dao->select()->from(TABLE_COMPANYS)->where(['id' => $qrscene])->getOneRow();
                            // 用户已注册 但是没有关联任何代理
                            //Beennn 2015-12-8 10:36:12 不允许成为自己的下级会员
                            if ($user['client_comid'] == 0 && $user['client_wechat_openid'] != $thiscompany['openid']) {
                                $this->Dao->update(TABLE_USER)->set(['client_comid' => $qrscene])->where(['client_id' => $uid])->exec();
                            }
                        } else {
                            $uid = NULL;
                        }
                        // <请注意> 如果扫描的用户没有注册，也就是clients没有对应的用户信息，uid是NULL，用户注册之后，则会更新company_users表的对应字段
                        $this->Dao->insert(TABLE_COMPANY_USERS, 'openid,comid,uid')->values([$this->openID, $qrscene, $uid])->exec();
                        // 提醒代理
                        $openid = $this->Dao->select('openid')->from(TABLE_COMPANYS)->where(['id' => $qrscene])->getOne();
                        // 发送消息
                        Messager::sendText(WechatSdk::getServiceAccessToken(), $openid, date('Y-m-d') . ' 有一名会员加入了');
                        // 提交事务
                        $this->Db->transcommit();
                    } catch (Exception $ex) {
                        // 回滚事务
                        $this->Db->transrollback();
                        // 出错写入记录
                        $this->log(sprintf("代理关联失败：openid:%s,comid:%s,错误信息:%s", $this->openID, $qrscene, $ex->getMessage()));
                    }
                }
            }

            // 关注消息
            $welcomeId = $this->wc->Db->getOne("SELECT `value` FROM `wshop_settings` WHERE `key` = 'welcomegmess';");
            if ($welcomeId > 0) {
                $this->wc->echoGmess($welcomeId);
            }

            $this->wc->autoEnvs();
        }

        /**
         * 处理按钮点击事件
         */
        if ($postObj->EventKey != '') {

            // 自定义按钮点击
            if (strpos('K_', $postObj->EventKey)) {
                $keyId = intval(str_replace('K_', '', $postObj->EventKey));
                if ($keyId > 0) {
                    $r = $this->wc->Db->getOneRow("SELECT * FROM `wshop_menu` WHERE `id` = $keyId;");
                    switch ($r['reltype']) {
                        case 0:
                            // 纯文字
                            $this->wc->responseText($r['relcontent']);
                            break;
                        case 1:
                            // 图文
                            $this->wc->echoGmess($r['relid']);
                            break;
                        case 2:
                            // 商品推荐
                    }
                }
            }

            // 签到按钮点击
            if ($postObj->EventKey == 'SIGN') {
                // uid
                $uid = $this->wc->Db->getOne("SELECT `client_id` FROM `clients` WHERE `client_wechat_openid` = '$this->openID';");
                // 返回积分数额
                $credit = $this->wc->Db->getOne("SELECT `value` FROM `wshop_settings` WHERE `key` = 'sign_credit';");
                // 签到限制天数
                $limitDay = $this->wc->Db->getOne("SELECT `value` FROM `wshop_settings` WHERE `key` = 'sign_daylim';");
                // 查找上一次签到记录
                $lastSign = $this->wc->Db->getOneRow("SELECT DATEDIFF(current_date(), `dt`) AS `d`,`dt` FROM `client_sign_record` WHERE `openid` = '$this->openID' order by `dt` DESC LIMIT 1;", false);
                // 比较
                if (isset($lastSign['dt']) && $lastSign['d'] >= $limitDay) {
                    // 尝试插入 签到记录 唯一索引控制
                    $r1 = $this->wc->Db->query("INSERT INTO `client_sign_record` (`dt`,`credit`,`openid`) VALUES (NOW(),$credit,'$this->openID');");
                    // 签到记录
                    if ($r1 !== false) {
                        // 增加积分
                        $this->wc->Db->query("UPDATE `clients` SET client_credit = client_credit + $credit WHERE `client_wechat_openid` = '$this->openID';");
                        // 积分记录
                        $r1 = $this->wc->Db->query("INSERT INTO `client_credit_record` (`dt`,`amount`,`reltype`,`uid`,`relid`) VALUES (NOW(),$credit,1,'$uid',0);");
                        $this->wc->responseText("签到成功，您获得{$credit}积分。");
                    }
                } else {
                    $this->wc->responseText("你最近已经签到过了。");
                }
            }
        }
    }

}
